import tkinter as tk
from tkinter import messagebox, ttk
from client import Client
from wseftsse import SigleEft30
import threading
import time

import tkinter as tk
from tkinter import messagebox, ttk
import threading
import time


# 主应用程序类
class Application(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("ETF监控工具")
        self.geometry("800x600")

        self.client = Client()
        self.etf30 = None


        self.create_widgets()

    def create_widgets(self):
        frame = tk.Frame(self)
        frame.pack(pady=10)
        # 创建标签

        self.label = tk.Label(frame, text="输入ETF编码(6位数字):")
        self.label.pack(side=tk.LEFT,pady=5)

        # 创建输入框
        self.entry = tk.Entry(frame, width=30)
        self.entry.insert(0, "511130")
        self.entry.pack(side=tk.LEFT,pady=5)

        # 创建按钮
        self.button = tk.Button(frame, text="监控EFT", command=self.fetch_etf_details)
        self.button.pack(side=tk.LEFT,pady=5)

        # 创建显示 ETF 详细信息的标签
        self.etf_info_frame = tk.Frame(self)
        self.etf_info_frame.pack(pady=10)

        self.etf_code_label = tk.Label(self.etf_info_frame, text="ETF Code: ")
        self.etf_code_label.grid(row=0, column=0, padx=5, pady=5)

        self.etf_name_label = tk.Label(self.etf_info_frame, text="Name: ")
        self.etf_name_label.grid(row=0, column=1, padx=5, pady=5)

        self.current_price_label = tk.Label(self.etf_info_frame, text="Current Price: ")
        self.current_price_label.grid(row=0, column=2, padx=5, pady=5)

        self.latest_net_value_label = tk.Label(self.etf_info_frame, text="Latest Net Value: ")
        self.latest_net_value_label.grid(row=1, column=0, padx=5, pady=5)

        self.highest_today_label = tk.Label(self.etf_info_frame, text="Highest Today: ")
        self.highest_today_label.grid(row=1, column=1, padx=5, pady=5)

        self.lowest_today_label = tk.Label(self.etf_info_frame, text="Lowest Today: ")
        self.lowest_today_label.grid(row=1, column=2, padx=5, pady=5)

        # 创建列表视图显示买入卖出提醒
        self.listbox_frame = tk.Frame(self)
        self.listbox_frame.pack(pady=10)

        self.listbox = tk.Listbox(self.listbox_frame, height=10, width=80)
        self.listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

        self.scrollbar = tk.Scrollbar(self.listbox_frame, orient=tk.VERTICAL)
        self.scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

        self.listbox.config(yscrollcommand=self.scrollbar.set)
        self.scrollbar.config(command=self.listbox.yview)

    def fetch_etf_details(self):

        etf_code = self.entry.get()
        if not etf_code:
            messagebox.showerror("Error", "ETF Code cannot be empty")
            return

        data = self.client.get_etf_details(etf_code)
        if data:
            self.entry.config(state='readonly')
            self.etf30 = SigleEft30(dm=etf_code)
            self.etf30.refreshbase()
            self.display_etf_details(data)
            self.start_update_thread()
        else:
            messagebox.showerror("Error", "Failed to fetch ETF details")

    def display_etf_details(self, data):
        # 更新标签内容
        self.etf_code_label.config(text=f"ETF代码: {data.get('code', '')}")
        self.etf_name_label.config(text=f"名称: {data.get('name', '')}")
        self.current_price_label.config(text=f"当前价格: {data.get('current_price', '')}")
        self.latest_net_value_label.config(text=f"净值: {data.get('latest_net_value', '')}")
        self.highest_today_label.config(text=f"日内最高: {data.get('highest_today', '')}")
        self.lowest_today_label.config(text=f"日内最低: {data.get('lowest_today', '')}")

        # 清空列表视图
        self.listbox.delete(0, tk.END)

    def start_update_thread(self):
        self.update_thread = threading.Thread(target=self.update_etf_data)
        self.update_thread.daemon = True
        self.update_thread.start()

    def update_etf_data(self):
        while True:
            time.sleep(5)
            print("===========")
            try:
                self.etf30.refreshsnap()
                self.etf30.refshline()
                self.update_labels_and_listbox()
            except:
                print("error")

    def update_labels_and_listbox(self):
        if self.etf30:
            data = {
                "name": self.etf30.base.get("FUND_NAME", ""),
                "code": self.etf30.dm,
                "current_price": self.etf30.snap.get("last", ""),
                "latest_net_value": self.etf30.nav,
                "highest_today": self.etf30.snap.get("high", ""),
                "lowest_today": self.etf30.snap.get("low", "")
            }
            self.display_etf_details(data)

            # 获取买入卖出提醒
            reminders = self.etf30.watch_etf()
            print(reminders)
            for reminder in reminders:
                self.listbox.insert(tk.END, f"{reminder['time']} | {reminder['price']} | {reminder['direction']} | {reminder['level']}")

    def on_closing(self):
        self.client.close()
        self.destroy()

if __name__ == "__main__":
    app = Application()
    app.protocol("WM_DELETE_WINDOW", app.on_closing)
    app.mainloop()
